<template>
  <div class="min-h-screen bg-gray-50">
    <div class="max-w-7xl mx-auto px-4 py-8">
      <div class="grid grid-cols-3 gap-8">
        <div class="col-span-2">
          <div class="bg-white p-6 rounded-lg shadow-md">
            <div class="flex items-center justify-between mb-6">
              <div class="flex items-center">
                <button class="mr-4 text-gray-600 hover:text-custom">
                  <h2 class="text-xl font-bold">{{ question?.question_text }}</h2>

                </button>
              </div>

            </div>

            <div class="space-y-6">
              <div class="bg-gray-50 p-6 rounded-lg">
                <div class="flex">
                  <h3 class="font-medium mb-4">解答</h3>
                  <el-button icon="el-icon-refresh" @click="refresh"
                    style="margin-left: 1rem;position:relative; bottom: .4rem;">交換</el-button>
                </div>


                <textarea v-model="user_answer"
                  class="w-full h-48 p-4 border border-gray-300 rounded-lg focus:border-custom focus:ring-1 focus:ring-custom"
                  placeholder="ここに解答を入力します..."></textarea>
                <div class="flex justify-between mt-4">

                  <button class="px-6 py-2 bg-custom text-white rounded-lg hover:bg-opacity-90" @click="sub">提出</button>

                  <button class="px-6 py-2 text-gray-600 hover:text-custom" @click="clear">クリア</button>
                </div>
              </div>
            </div>
          </div>
        </div>

        <div class="bg-white p-6 rounded-lg shadow-md h-fit">
          <div class="space-y-6">
            <div class="p-4 bg-gray-50 rounded-lg">
              <h4 class="font-medium text-sm mb-3">関連知識</h4>
              <ul class="text-sm text-gray-600 space-y-2">
                <li v-for="(item, index) in category_list" :key="index"
                  style="cursor: pointer;">{{ item }}</li>
              </ul>
            </div>
          </div>
        </div>
      </div>
    </div>

  </div>
</template>

<script>
import { post,get } from "@/http/axios"
export default {
  name: 'MathHelper',
  data() {
    return {
      hidden: false,
      categroy_list: [],
      id: null,
      branch_id: null,
      category_list:[],
      user_answer: null,
      exercise_id: null,
      answer_id: null,
      count: 0,
      totalCount: 0,
      question: null,
      // 数据定义
    };
  },
  async created() {
    this.id = this.$route.query.id
    sessionStorage.setItem("category_id", this.id)
  },
  async mounted() {

    this.$nextTick(async () => {
      sessionStorage.removeItem("answer")
      this.branch_id = this.$route.query.branch_id
      const loading = this.$loading({
        lock: true,
        text: 'Loading',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.7)'
      });
      if (this.$route.query.next) {
        await this.getQuestions(1)
        loading.close()

      } else if (this.$route.query.exercise_id) {
        this.exercise_id = this.$route.query.exercise_id
        this.answer_id = this.$route.query.answer_id
        await this.getSign()
        loading.close()
      } else if (this.$route.query.user_question) {
        await this.getQuestions(2)
        loading.close()
      } else {
        await this.questions()
        loading.close()
      }


    })
  },
  methods: {
    async synthesizeSpeech(text, exercise_id) {
      const audioData = await post("https://texttospeech.googleapis.com/v1/text:synthesize?key=AIzaSyD9svMNBcCUbDn86-QdHCtUrY2Hp1Nn2V8",
        {
          input: {
            text: text
          },
          voice: {
            "languageCode": "ja-JP",
            "name": "ja-JP-Wavenet-A",
            "ssmlGender": "FEMALE",
          },
          audioConfig: {
            "audioEncoding": "MP3",
            "speakingRate": 1.0,
            "pitch": 0,
          }
        }
      )
      const audioContent = audioData.data.audioContent;
      const audioDatas = Uint8Array.from(atob(audioContent), c => c.charCodeAt(0)); // Base64 解码

      const formData = new FormData();
      const blob = new Blob([audioDatas.buffer], { type: 'audio/mp3' });
      formData.append('file', blob);
      let qq = await post("/audioUploads/" + exercise_id, formData)
      return qq.data.data
    },
    async toView(id) {
      this.user_answer = ""
      this.question = null
      this.id = id
      const loading = this.$loading({
        lock: true,
        text: 'Loading',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.7)'
      });
      await this.questions()
      loading.close()
    },

    async refresh() {
      try {
        const loading = this.$loading({
        lock: true,
        text: 'Loading',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.7)'
      });
        let data=null
        if(this.$route.query.user_question){
          data = await post("/try_user_gen", { category_id: this.id, exercise_id: this.question.exercise_id,source:  this.question.source_value,category_name:this.question.category_name})
        }else{
          data = await post("/try_gen", { category_id: this.id, exercise_id: this.question.exercise_id })
   
        }
        loading.close()
        if (data.data.code == "success") {
          this.question = data.data.data
          this.getSign()
        } else {
          this.$message.error("問題を取るのに失敗")
        }
      } catch (error) {
        loading.close()
        this.$message.error("接続タイムアウトです")
      }

    },
    clear() {
      this.user_answer = ""
    },
    async sub() {
      if (!this.user_answer) {
        this.$message.error("答えを入力します。")
        return
      }

      let obj = {
        question: this.question.question_text,
        answer: this.question.answer_text,
        user_answer: this.user_answer,
        category_id: this.id,
        exercise_id: this.question.exercise_id,
        branch_id: this.branch_id,

      }
      const loading = this.$loading({
        lock: true,
        text: 'Loading',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.7)'
      });
      if (this.$route.query.user_question) {
        let data = await post("/answer_user", { ...obj, answer_id: this.answer_id })

        if (data.data.code == "success") {


          sessionStorage.removeItem("answer_user")
          let url = await this.synthesizeSpeech(data?.data?.data.solution_idea, data?.data?.data.exercise_id)
          sessionStorage.setItem("answer_user", JSON.stringify({ ...data?.data?.data, totaCount: data?.data?.totaCount, count: data?.data?.count, url }))
          this.$message.success("提出成功")
          this.$router.replace({ path: "/answer_user", query: { count: this.count, totalCount: this.totalCount } })
          loading.close()
        } else {
          this.$message.error("提出に失敗")
          loading.close()
        }

      return
      } 
      if (this.$route.query.hidden) {
        let data = await post("/answer", { ...obj, answer_id: this.answer_id })
        console.log(data?.data?.data.solution_idea)
        let url = await this.synthesizeSpeech(data?.data?.data.solution_idea, data?.data?.data.exercise_id)
        sessionStorage.setItem("answer", JSON.stringify({ ...data?.data?.data, totaCount: data?.data?.totaCount, count: data?.data?.count, url }))
        this.$message.success("提出成功")

        this.$router.replace({ path: "/answer_sub", query: { hidden: this.$route.query.hidden } })
        return
      }
      if (this.exercise_id && this.answer_id) {

        let data = await post("/answer", { ...obj, answer_id: this.answer_id })

        if (data.data.code == "success") {

          loading.close()
          sessionStorage.removeItem("answer")
          let url = await this.synthesizeSpeech(data?.data?.data.solution_idea, data?.data?.data.exercise_id)
          sessionStorage.setItem("answer", JSON.stringify({ ...data?.data?.data, totaCount: data?.data?.totaCount, count: data?.data?.count, url }))
          this.$message.success("提出成功")
          this.$router.replace({ path: "/answer_sub", query: { count: this.count, totalCount: this.totalCount } })

        } else {
          this.$message.error("提出に失敗")
          loading.close()
        }

      } else {
        let data = await post("/answer", obj)
        if (data.data.code == "success") {

          let url = await this.synthesizeSpeech(data?.data?.data.solution_idea, data?.data?.data.exercise_id)
          sessionStorage.setItem("answer", JSON.stringify({ ...data?.data?.data, totaCount: data?.data?.totaCount, count: data?.data?.count, url }))
          this.$message.success("提出成功")
          this.$router.replace({ path: "/answer_sub", query: { count: this.count, totalCount: this.totalCount } })

        } else {
          this.$message.error("提出に失敗")

        }
      }
    },
    async getSign() {
      try {
        let data_question = null
        if(this.$route.query.user||this.$route.query.user_question){
          data_question = await post("/get_user_question_sign", { exercise_id: this.exercise_id })
        }else{
          data_question = await post("/get_question_sign", { exercise_id: this.exercise_id })
        }
        if (data_question.data.code == "success") {
          this.question = data_question.data.data
          this.exercise_id = data_question.data.data.exercise_id

          this.count = this.question.count
          this.totalCount = this.question.total_count
        } else {
          this.$message.error("問題を取るのに失敗")
        }
      } catch (error) {
        this.$message.error("接続タイムアウトです")
      }
    },
    async getQuestions(type) {
      try {
        let data_question = null
        if (type == 1) {
          data_question = await post("/get_question", { category_id: this.id, branch_id: this.branch_id })
          let data = await post("/createCategory",{question:data_question.data.data.category_name})
          this.category_list = data.data.data

        } else {
          data_question = await post("/get_user_question", { category_id: this.id, branch_id: this.branch_id })
        }
        if (data_question.data.code == "success") {
          this.question = data_question.data.data
          this.exercise_id = data_question.data.data.exercise_id
          this.count = this.question.count
          this.totalCount = this.question.total_count
        } else {
          this.$message.error("問題を取るのに失敗")
        }
      } catch (error) {
        console.log(error)
        this.$message.error("接続タイムアウトです")
      }
    },
    async questions() {
      let obj = {
        category_id: this.id
      }
      try {
        let data = await post("/select_sub", obj)
        if (data.data.code == "success") {
          this.branch_id = data.data.data

         await this.getQuestions(1)

        }
      } catch (error) {
        this.$message.error("接続タイムアウトです")

      }

    },

  }
};
</script>

<style scoped>
/* 样式定义 */
</style>
